package com.pers.springcloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.pers.springcloud.service.PaymentHystrixServiceApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: 黄建
 * @Date: 2020/3/9 15:28
 */
@RestController
@RequestMapping("/consumer")
//设置全局默认备用方法
//@DefaultProperties(defaultFallback = "globalFallBackMethod",commandProperties = {
//        @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "10000")
//})
public class OrderHystrixController {

    @Autowired
    private PaymentHystrixServiceApi paymentHystrixServiceApi;


    @GetMapping(value = "/payment/hystrix/timeout/{id}",produces = MediaType.APPLICATION_JSON_VALUE)
    /*@HystrixCommand(fallbackMethod = "paymentInfoTimeOutHandlerFallbackMethod",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
    })*/
    public String paymentInfo_Timeout(@PathVariable("id") Integer id){
        String s = paymentHystrixServiceApi.paymentInfo_Timeout(id);
        System.out.println("timeout:"+s);
        return s;
    }

    @GetMapping(value = "/payment/hystrix/ok/{id}",produces = MediaType.APPLICATION_JSON_VALUE)
    public String paymentInfo_OK(@PathVariable("id") Integer id){
        String s = paymentHystrixServiceApi.paymentInfo_OK(id);
        System.out.println("ok:"+s);
        return s;
    }

    public String paymentInfoTimeOutHandlerFallbackMethod(@PathVariable("id") Integer id) {
        return "80消费者端口，调用支付端口支付系统繁忙请十秒后重试";
    }

    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),// 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")//失败率达到多少后跳闸
    })
    @GetMapping(value = "/payment/circuit/{id}",produces = MediaType.APPLICATION_JSON_VALUE)
    public String paymentCircuitBreaker(@PathVariable("id") Integer id){
        String s = paymentHystrixServiceApi.paymentCircuitBreaker(id);
        System.out.println("result:"+s);
        return s;
    }

    public String globalFallBackMethod() {
        return "80消费者端口，globalFallBackMethod";
    }

}
